package com.imu.purse.api.controller.trade;

import javax.servlet.http.HttpServletRequest;

import com.imu.purse.modules.base.entity.SysConfigEntity;
import com.imu.purse.modules.base.service.SysConfigService;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.imu.common.annotation.IgnoreAuth;
import com.imu.common.exception.ErrorDesc;
import com.imu.common.exception.ErrorUtil;
import com.imu.common.utils.R;
import com.imu.common.validator.ValidatorUtils;
import com.imu.common.validator.group.AddGroup;
import com.imu.common.validator.group.UpdateGroup;
import com.imu.purse.api.controller.ApiAbstractController;
import com.imu.purse.modules.app.entity.ImuUserEntity;
import com.imu.purse.modules.app.service.ImuUserService;
import com.imu.purse.modules.trade.entity.PriequityEntity;
import com.imu.purse.modules.trade.form.PriequityForm;
import com.imu.purse.modules.trade.service.PriequityService;
import com.imu.security.SessionKeys;
import com.imu.security.SessionTokenProviderFactory;
import com.imu.utils.RSASignature;
import com.xiaoleilu.hutool.bean.BeanUtil;
import com.xiaoleilu.hutool.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * 私募接口
 * @author sunhongwei
 * @email sunhongwei@gmail.com
 * @date 2018-03-22 17:27
 */
@RestController
@RequestMapping("/api/priequity")
@Api(tags="私募接口")
public class ApiPriequityController extends ApiAbstractController
{
    /**
     * 私募
     * PriequityEntity dto 
     */
    @IgnoreAuth
    @PostMapping()
    @ApiOperation(value = "私募")
    @ApiImplicitParams({
    	@ApiImplicitParam(paramType = "body", dataType="PriequityForm", name = "dto", value = "私募", required = true)
    })
    public R add(@RequestHeader("X-IMU-SECRET") String secret, @RequestHeader("X-IMU-SESSION") String token, @RequestBody PriequityForm dto, HttpServletRequest request)
    {
        SysConfigEntity sysConfigEntity = sysConfigService.findByKey("PRI_ENABLE_KEY");
        if(null == sysConfigEntity || StrUtil.isBlank(sysConfigEntity.getValue()) || StrUtil.isNotBlank(sysConfigEntity.getValue())) {
        	return R.error(110, "一期私募已结束，请关注后期私募。");
        }
        
        if("0".equals(sysConfigEntity.getValue())) return R.error(ErrorDesc.PRI_ENABLE_KEY.getCode(), sysConfigEntity.getRemark());

    	//表单校验
        ValidatorUtils.validateEntity(dto, AddGroup.class);
        
        //验证最大贝壳数
        if(null == dto.getBuyNum() || dto.getBuyNum().intValue() > 500) 
        {
        	return ErrorUtil.errorMesg(request,ErrorDesc.BK_QUANTUM_500);
        }
        
        //是否验证签名
        if(null == verify || verify.booleanValue())
        {
        	String  sign = request.getHeader(SessionKeys.SIGN.toString());
            if(!RSASignature.verifySign(JSON.toJSONString(dto),sign, this.pubKey))
            {
            	return ErrorUtil.errorMesg(request,ErrorDesc.SIGN_VERIFY_ERR);
            }
        }
        
        //判断Session 是否存在
        String uid = SessionTokenProviderFactory.getSessionTokenProvider().getUserId(secret, token);
        if (StrUtil.isBlank(uid)) {
            return ErrorUtil.errorMesg(request, ErrorDesc.SESSION_EMPTY);
        }
     
        //验证图片验证码是否正确
        String picPass = dto.getAcode().toLowerCase();
        String str = redisTemplate.opsForValue().get(picPass);
        if(StrUtil.isBlank(str)){
            return ErrorUtil.errorMesg(request,ErrorDesc.PHOTO_ACODE_ERROR);
        }
        
        //验证支付密码
        ImuUserEntity user = userService.findById(Long.valueOf(uid));
        //校验支付密码正确性
        if(user == null || StrUtil.isBlank(user.getPayPwd()) || !user.getPayPwd().equals(new Sha256Hash(dto.getPwd()).toHex()))
        {
            return ErrorUtil.errorMesg(request,ErrorDesc.TRADE_PWD_ERROR);
        }
        
        //判断用户是否可以转账标识
        if("0".equals(String.valueOf(user.getStatetrans()))) return ErrorUtil.errorMesg(request, ErrorDesc.USER_TRANS_ENABLE);
        
        //插入私募信息
        PriequityEntity entity = new PriequityEntity();
        BeanUtil.copyProperties(dto, entity);
        entity.setUserId(Long.valueOf(uid));
        //删除验证码
        redisTemplate.delete(picPass);
        return R.ok(1).put("data", service.priMoney("priequity:" + uid, entity));
    }
    
    /**
     * 私募
     * PriequityEntity dto 
     */
    @IgnoreAuth
    @PutMapping()
    @ApiOperation(value = "私募GET")
    @ApiImplicitParams({
    	@ApiImplicitParam(paramType = "body", dataType="PriequityForm", name = "dto", value = "私募", required = true)
    })
    public R get(@RequestHeader("X-IMU-SECRET") String secret, @RequestHeader("X-IMU-SESSION") String token, @RequestBody PriequityForm dto, HttpServletRequest request)
    {
        SysConfigEntity sysConfigEntity = sysConfigService.findByKey("PRI_ENABLE_KEY");
        if("0".equals(sysConfigEntity.getValue())) return R.error(ErrorDesc.PRI_ENABLE_KEY.getCode(), sysConfigEntity.getRemark());

    	//表单校验
        ValidatorUtils.validateEntity(dto, UpdateGroup.class);
        
        //验证最大贝壳数
        if(null == dto.getBuyNum() || dto.getBuyNum().intValue() > 2500)
        {
        	return ErrorUtil.errorMesg(request,ErrorDesc.BK_QUANTUM_2500);
        }

        String picPass = dto.getAcode().toLowerCase();
        //是否验证签名
        if(null == verify || verify.booleanValue())
        {
        	String  sign = request.getHeader(SessionKeys.SIGN.toString());
            if(!RSASignature.verifySign(JSON.toJSONString(dto),sign, this.pubKey))
            {
            	return ErrorUtil.errorMesg(request,ErrorDesc.SIGN_VERIFY_ERR);
            }
            
            //验证图片验证码是否正确
            String str = redisTemplate.opsForValue().get(picPass);
            if(StrUtil.isBlank(str)){
                return ErrorUtil.errorMesg(request,ErrorDesc.PHOTO_ACODE_ERROR);
            }
        }
        
        //判断Session 是否存在
        String uid = SessionTokenProviderFactory.getSessionTokenProvider().getUserId(secret, token);
        if (StrUtil.isBlank(uid)) {
            return ErrorUtil.errorMesg(request, ErrorDesc.SESSION_EMPTY);
        }
        
        //验证支付密码
        ImuUserEntity user = userService.findById(Long.valueOf(uid));

        //校验支付密码正确性
        if(user == null || StrUtil.isBlank(user.getPayPwd()) || !user.getPayPwd().equals(new Sha256Hash(dto.getPwd()).toHex()))
        {
            return ErrorUtil.errorMesg(request,ErrorDesc.TRADE_PWD_ERROR);
        }
        
        //判断用户是否可以转账标识
        if("0".equals(String.valueOf(user.getStatetrans()))) return ErrorUtil.errorMesg(request, ErrorDesc.USER_TRANS_ENABLE);
        
        //插入私募信息
        PriequityEntity entity = new PriequityEntity();
        BeanUtil.copyProperties(dto, entity);
        entity.setUserId(Long.valueOf(uid));
        //删除验证码
        redisTemplate.delete(picPass);
        return R.ok(1).put("data", service.priGet("priequity:get", entity));
    }
    
    @Autowired
    private PriequityService service;

	@Autowired
	private ImuUserService userService;
	
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private SysConfigService sysConfigService;
    
    /****
     *公钥解密
     */
    @Value("${app.pay.pub-key}")
    private String pubKey;
    
    /****
     *是否验证签名
     */
    @Value("${app.priequity.verify}")
    private Boolean verify;
}
